package org.soarsky.wealthchengdu.module.focus;

import java.util.ArrayList;
import java.util.List;

import m.framework.ui.SlidingMenu;

import org.soarsky.wealthchengdu.R;
import org.soarsky.wealthchengdu.appliction.MyAppliction;
import org.soarsky.wealthchengdu.db.DBtool;
import org.soarsky.wealthchengdu.entity.JsonResult;
import org.soarsky.wealthchengdu.entity.LogonResult;
import org.soarsky.wealthchengdu.entity.NewsContentData;
import org.soarsky.wealthchengdu.imageCache.CacheMemUtil;
import org.soarsky.wealthchengdu.imageCache.ImageLoader;
import org.soarsky.wealthchengdu.imageCache.ImageLoader.ImageCallback;
import org.soarsky.wealthchengdu.language.LanguageUtil;
import org.soarsky.wealthchengdu.module.comment.CommentActivity;
import org.soarsky.wealthchengdu.network.ParserResults;
import org.soarsky.wealthchengdu.share.ShareAllGird;
import org.soarsky.wealthchengdu.util.Config;
import org.soarsky.wealthchengdu.view.ALLSendDialog;

import android.app.Activity;
import android.app.LocalActivityManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import cn.sharesdk.framework.AbstractWeibo;

/**
 * 滑动界面
 * 
 * @author Administrator
 * 
 */
public class FocusActivity extends Activity implements OnClickListener {

	private ViewPager mPager;// 页卡内容
	private List<View> listViews; // Tab页面列表
	private LocalActivityManager manager = null;
	private final Context context = FocusActivity.this;
	private ParserResults service;
	List<NewsContentData> datas;
	private int position = 0;
	private ImageView focus_iv_one;
	private ImageView focus_iv_two;
	private ImageView focus_iv_three;
	private ImageView focus_iv_four;
	private ImageView titleReturn;
	private TextView titleName;
	private SlidingMenu menu;
	public String TEST_IMAGE;
	private Cursor cusor;
	private PopupWindow mPopupWindow;
	private LanguageUtil util;
	private String[] list;
	String fenxiang;
	String imgUrl;
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);// 取消标题
		setContentView(R.layout.activity_delitviewflipper);

		manager = new LocalActivityManager(this, true);
		manager.dispatchCreate(savedInstanceState);
		service = new ParserResults();
		menu = new SlidingMenu(this);
		AbstractWeibo.initSDK(this);
		Bundle bundler = this.getIntent().getExtras();
		position = bundler.getInt("position");
		InitTextView();
		setdata();
	}

	/**
	 * 初始化头标
	 */
	private void InitTextView() {
		if (MyAppliction.ifcollect) {
			InitViewPager();
		} else {
			getNews(MyAppliction.list);
		}
	}

	/**
	 * 初始化ViewPager
	 */
	private void InitViewPager() {
		titleName=(TextView)findViewById(R.id.title_tv_text);
		util = Config.changeLanguage(MyAppliction.mCn);
		list = util.getHomeGridNames();
		titleName.setText(list[MyAppliction.mChoose]);
		mPager = (ViewPager) findViewById(R.id.viewpagerLayout);
		listViews = new ArrayList<View>();
		MyPagerAdapter mpAdapter = new MyPagerAdapter(listViews);

		Intent intent = new Intent(context, FocusDelitScroll.class);

		if (MyAppliction.ifcollect) {
			if (MyAppliction.collectlistID != null
					&& MyAppliction.collectlistID.size() > 0) {
				for (int i = 0; i < MyAppliction.collectlistID.size(); i++) {
					FocusDelitScroll.setID(MyAppliction.collectlistID.get(i));
					listViews.add(getView("web9" + i, intent));
				}
			}
		} else {
			if (datas != null && datas.size() > 0) {
				for (int i = 0; i < datas.size(); i++) {
					FocusDelitScroll.setID(datas.get(i));
					listViews.add(getView("web9" + i, intent));
				}
			}
		}

		mPager.setAdapter(mpAdapter);
		mPager.setCurrentItem(position);
		mPager.setOnPageChangeListener(new MyOnPageChangeListener());
	}

	/**
	 * ViewPager适配器
	 */
	public class MyPagerAdapter extends PagerAdapter {
		public List<View> mListViews;

		public MyPagerAdapter(List<View> mListViews) {
			this.mListViews = mListViews;
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView(mListViews.get(arg1));
		}

		@Override
		public void finishUpdate(View arg0) {
		}

		@Override
		public int getCount() {
			return mListViews.size();
		}

		@Override
		public Object instantiateItem(View arg0, int arg1) {
			((ViewPager) arg0).addView(mListViews.get(arg1), 0);
			return mListViews.get(arg1);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == (arg1);
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {
		}
	}

	/**
	 * 头标点击监听
	 */
	public class MyOnClickListener implements View.OnClickListener {
		private int index = 0;

		public MyOnClickListener(int i) {
			index = i;
		}

		@Override
		public void onClick(View v) {
			mPager.setCurrentItem(index);
		}
	};

	/**
	 * 页卡切换监听
	 */
	public class MyOnPageChangeListener implements OnPageChangeListener {

		@Override
		public void onPageSelected(int arg0) {
			position = arg0;
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}
	}

	private View getView(String id, Intent intent) {
		return manager.startActivity(id, intent).getDecorView();
	}

	// 获取新闻内容
	public void getNews(final List<String> ids) {
		ALLSendDialog.showdialog(this);
		if (ids == null || ids.size() == 0)
			return;
		new AsyncTask<Void, Void, List<NewsContentData>>() {

			@Override
			protected List<NewsContentData> doInBackground(Void... params) {
				// TODO Auto-generated method stub
				datas = new ArrayList<NewsContentData>();
				NewsContentData data;
				JsonResult<NewsContentData> result;
				for (String id : ids) {
					try {
						result = service.getNewsContent(id);
						if (result != null && !result.isError()) {
							data = result.getData();
							if (data != null) {
								datas.add(data);
								Log.e("tag", data.getContent());
							}
						}
					} catch (Exception e) {
						ALLSendDialog.dimssdialog();
					}
				}
				
				return datas.size() == 0 ? null : datas;
			}

			protected void onPostExecute(java.util.List<NewsContentData> result) {
				// 结果不为null 结果正确
				InitViewPager();
				ALLSendDialog.dimssdialog();
			};
		}.execute();

	}

	public void setdata() {
		// 底部栏的操作按钮
		focus_iv_one = (ImageView) findViewById(R.id.focus_iv_one);
		focus_iv_two = (ImageView) findViewById(R.id.focus_iv_two);
		focus_iv_three = (ImageView) findViewById(R.id.focus_iv_three);
		focus_iv_four = (ImageView) findViewById(R.id.focus_iv_four);
		titleReturn = (ImageView) findViewById(R.id.title_iv_img);
		TextView setTieleText = (TextView) findViewById(R.id.title_tv_text);
		// setTieleText.setText(list[MyAppliction.mChoose]);
		// // 显示页面内容的webview
		focus_iv_one.setOnClickListener(this);
		focus_iv_two.setOnClickListener(this);
		focus_iv_three.setOnClickListener(this);
		focus_iv_four.setOnClickListener(this);
		titleReturn.setOnClickListener(this);

	}

	// 使用快捷分享完成图文分享
	private void showGrid(boolean silent) {
		Intent i = new Intent(menu.getContext(), ShareAllGird.class);
		// 分享时Notification的图标
		i.putExtra("notif_icon", R.drawable.ic_launcher);
		// 分享时Notification的标题
		i.putExtra("notif_title", menu.getContext()
				.getString(R.string.app_name));

		// address是接收人地址，仅在信息和邮件使用，否则可以不提供
		i.putExtra("address", "12345678901");
		// title标题，在印象笔记、邮箱、信息、微信（包括好友和朋友圈）、人人网和QQ空间使用，否则可以不提供
		i.putExtra("title", menu.getContext().getString(R.string.share));
		/** 这个自己的分享标题 */
		// titleUrl是标题的网络链接，仅在QQ空间使用，否则可以不提供
		i.putExtra("titleUrl", "http://sharesdk.cn");
		// text是分享文本，所有平台都需要这个字段
		i.putExtra("text", fenxiang);
		/** 这个自己输入分享内容 */
		// imagePath是本地的图片路径，在豆瓣、Facebook、网易微博、新浪微博、腾讯微博、Twitter、邮箱、
		// 信息和微信（包括好友和朋友圈）图片分享中使用，否则可以不提供
		i.putExtra("imagePath", TEST_IMAGE);
		// imageUrl是网络的图片路径，仅在人人网和QQ空间使用，否则可以不提供
		i.putExtra("imageUrl",
				"http://sharesdk.cn/Public/Frontend/images/logo.png");
		// url仅在人人网和微信（包括好友和朋友圈）中使用，否则可以不提供
		i.putExtra("url", "http://sharesdk.cn");
		// thumbPath是缩略图的本地路径，仅在微信（包括好友和朋友圈）中使用，否则可以不提供
		i.putExtra("thumbPath", TEST_IMAGE);
		// appPath是待分享应用程序的本地路劲，仅在微信（包括好友和朋友圈）中使用，否则可以不提供
		i.putExtra("appPath", TEST_IMAGE);
		// comment是我对这条分享的评论，仅在人人网和QQ空间使用，否则可以不提供
		i.putExtra("comment", menu.getContext().getString(R.string.share));
		// site是分享此内容的网站名称，仅在QQ空间使用，否则可以不提供
		i.putExtra("site", menu.getContext().getString(R.string.app_name));
		// siteUrl是分享此内容的网站地址，仅在QQ空间使用，否则可以不提供
		i.putExtra("siteUrl", "http://sharesdk.cn");

		// 是否直接分享
		i.putExtra("silent", silent);
		menu.getContext().startActivity(i);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.focus_iv_one:
			focus_iv_one.setImageResource(R.xml.praise);
			String s = MyAppliction.ID;
			loadDatas();
			break;
		case R.id.title_iv_img:
			this.finish();

			break;
		case R.id.focus_iv_two:
			focus_iv_two.setImageResource(R.xml.comment);
			Intent intent = new Intent(this, CommentActivity.class);
			if (MyAppliction.ifcollect) {
				MyAppliction.ID = MyAppliction.collectlistID.get(position)
						.getId();
			} else {
				MyAppliction.ID = datas.get(position).getId();
			}
			this.startActivity(intent);
			break;
		case R.id.focus_iv_three:
			focus_iv_three.setImageResource(R.xml.collect);
			if (MyAppliction.ifcollect) {
				cusor = DBtool.getDBTool(this).select(
						MyAppliction.collectlistID.get(position).getId());
			} else {
				cusor = DBtool.getDBTool(this).select(
						datas.get(position).getId());
			}

			if (cusor.getCount() > 0) {
				Toast.makeText(this, "取消收藏", Toast.LENGTH_LONG).show();
				DBtool.getDBTool(this).deleteData(MyAppliction.ID);
				focus_iv_three.setImageResource(R.drawable.focus_btn_three);
			} else {
				DBtool.getDBTool(this).insertData(datas.get(position));
				focus_iv_three.setImageResource(R.drawable.focus_btn_three_up);
				initPopupWindow();
				showPopupWindow(focus_iv_three);
			}
			break;
		case R.id.focus_iv_four:
			if (MyAppliction.ifcollect) {
				imgUrl=MyAppliction.collectlistID.get(position).getImg();
				loadImage(imgUrl);
				fenxiang=MyAppliction.collectlistID.get(position).getSource()+":"+MyAppliction.collectlistID.get(position).getTitle();
			} else {
				fenxiang=datas.get(position).getSource()+":"+datas.get(position).getTitle();
			}
			showGrid(true);
			break;
		default:
			break;
		}

	}

	

	private void loadImage(final String url) {

		// Bitmap bm = CacheMemUtil.getImage(url);
		Bitmap bm = CacheMemUtil.getImageFromCache(url); // 第一步，仅仅只从内存中读取
		if (bm != null) {
			// 包括从本地获取的，未进行图片处理的图片
			// bm = ImageUtil.zoomBitmap(bm, iconWidth, iconHeight);// 缩放处理
			// bm = ImageUtil.getRoundedCornerBitmap(bm, corners);// 圆角处理
			// CacheMemUtil.putImage2Cache(url, bm);

		} else {

			ImageLoader.getInstance().loadBitmap(url, new ImageCallback() {

				public void imageLoaded(Bitmap bm) {
					if (bm != null) {
						// //以下两行，根本不该在这里调用，应该在存在本地之前，而不是读取显示时才做处理
						// bm = ImageUtil.zoomBitmap(bm, iconWidth,
						// iconHeight);// 缩放处理
						// bm = ImageUtil.getRoundedCornerBitmap(bm, corners);//
						// 圆角处理
						CacheMemUtil.putImage2Cache(url, bm);
						// image.setImageBitmap(bm); //不能使用这句方法，否则会在加载完之前错误显示
					}
				}
			});
		}

	}
	
	
	private void loadDatas() {
		new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected Boolean doInBackground(Void... params) {
				// TODO Auto-generated method stub
				getLogon();
				try {
					JsonResult<String> jsonResult = service .sendVote(MyAppliction.ID);
					if (jsonResult == null)
						return false;
					if (jsonResult.isError()) {
						error(jsonResult);
						// 错误处理
						return false;
					} 
				} catch (Exception e) {
					// TODO Auto-generated catch block
				}
				return false;
			}

			protected void onPostExecute(Boolean result) {
				// UI更新操作
				if (result) {
				
					
					// CacheMemUtil.getImageFromCache(imgUrl);
				} else {

				}

			};
		}.execute();
	}
	
	// 必须先登录
	private void getLogon() {
		try {
			JsonResult<LogonResult> jsonResult = service.authLogon("张三");
			if (jsonResult != null) {
				if (jsonResult.isError()) {
					error(jsonResult);
				} else {// 登录成功
					System.out.println(jsonResult.getData().getUserId() + "==="
							+ jsonResult.getData().getNickName());
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println(e.toString() + "===");
		}
	}
	
	private static void error(JsonResult<?> jsonResult) {
		System.out.println("错误码:" + jsonResult.getCode() + "===错误信息:"
				+ jsonResult.getMsg());
	}

	private void initPopupWindow() {
		View view = LayoutInflater.from(this).inflate(R.layout.popupwindow,
				null);

		mPopupWindow = new PopupWindow(view, LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		// mPopupWindow.setBackgroundDrawable(new
		// BitmapDrawable());//必须设置background才能消失
		mPopupWindow.setBackgroundDrawable(this.getResources().getDrawable(
				R.drawable.popuwindow));
		mPopupWindow.setOutsideTouchable(true);
		TextView textView = (TextView) view.findViewById(R.id.popuwindow_text);
		textView.setText("收藏成功");
		// 自定义动画
		// mPopupWindow.setAnimationStyle(R.style.PopupAnimation);
		// 使用系统动画
		mPopupWindow.setAnimationStyle(android.R.style.Animation_Dialog);
		mPopupWindow.update();
		mPopupWindow.setTouchable(true);
		mPopupWindow.setFocusable(true);
	}

	private void showPopupWindow(View view) {
		if (!mPopupWindow.isShowing()) {
			// mPopupWindow.showAsDropDown(view,0,0);
			mPopupWindow.showAtLocation(view, Gravity.CENTER, 100, 430);
		}
	}
}